package cn.com.dhcc.turbo.dao.monitor;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import cn.com.dhcc.app.core.CM;
import cn.com.dhcc.app.core.dao.BaseDao;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.turbo.entity.monitor.QuotaValueHistory;
import cn.com.dhcc.turbo.entity.monitor.QuotaValueOnTime;
import cn.com.dhcc.turbo.entity.monitor.QuotaValueOnTime.QuotaHadlerStatus;
import cn.com.dhcc.turbo.entity.monitor.wapper.QuotaValueHistoryRowWapper;
import cn.com.dhcc.turbo.entity.monitor.wapper.QuotaValueOnTimeRowWapper;
import cn.com.dhcc.turbo.service.monitor.MonitorQuotaStatic.ALERT_PIPELINE;
@Repository
public class QuotaValueOnTimeDao  extends BaseDao {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.TURBO);

	/**
	 * 获取数据发送量
	 * @param quota_code
	 * @return
	 * @throws DaoException
	 */
	public List<QuotaValueOnTime> getSendFlowHourList(String quotaCode,String ownerId) throws DaoException {
		String msg = "";
		String sql = "select t1.hour stime,  case  when t2.sumval is null and to_date(t1.hour,'hh24') < to_date(to_char(sysdate, 'hh24'),'hh24')  then  '0'  else  t2.sumval  end sumval"
							+" from (select to_char(to_date('00', 'hh24') + (rownum - 1) / 24, 'hh24') hour "
							+" from dual t "
							+"        connect by rownum <= 24) t1 "
							+"   left join (select to_char(t.mtime, 'hh24') stime, "
							+"                    max(t.current_value1) sumval "
							+"               from  " + SI_TABLE("TURBO_MONITOR_ONTIME")+" t "
							+"             where t.quota_code = ? and (? is null or t.owner_id=?)"
							+"               and t.mtime >= to_date(to_char(sysdate, 'yyyy-mm-dd') || ' 00:00:00', 'yyyy-mm-dd hh24:mi:ss') "
							+"                and t.mtime <=to_date(to_char(sysdate, 'yyyy-mm-dd') || ' 23:59:59','yyyy-mm-dd hh24:mi:ss') "
							+"				and t.mtime in"
							+"							(select max(mtime)"
							+"		                       from  " + SI_TABLE("TURBO_MONITOR_ONTIME")
							+"		                      where quota_code =?"
							+"		                        and owner_id =?"
							+"		                      group by to_char(mtime, 'yyyy-mm-dd hh24'))"
							+"              group by to_char(t.mtime, 'hh24') "
							+"               order by to_char(t.mtime, 'hh24')) t2 "
							+"    on t1.hour = t2.stime "
							+"  group by t1.hour, t2.stime, t2.sumval "
							+"  order by t1.hour";

		try {
			return CM.getDao().list("获取数据发送量", sql, new QuotaValueOnTimeRowWapper(),new Object[] {quotaCode,ownerId,ownerId,quotaCode,ownerId});
		} catch (DaoException e) {
			msg = "获取数据发送送量";
			logger.error(msg, e);
			throw new DaoException(msg, e);
		}
	}
	/**
	 * 获取未处理告警列表
	 * @param pager
	 * @param condition
	 * @return
	 * @throws DaoException
	 */
	public PagerData<QuotaValueOnTime> alertlist(Pager pager, WhereCondition condition)
			throws DaoException {
		String sql = "select	distinct t.id, t.quota_code, t2.name quota_name, t.alert_msg,t.mtime,t2.alter_level,t.remark,t.handler_time "
							+" from 	 " + SI_TABLE("turbo_monitor_ontime")+" t "
							+"  	left 	join  " + SI_TABLE("turbo_monitor_quota")+" t2 "
							+"  	 on 	t.quota_code = t2.code "
							+" where t.needalert = '1'  and (t.status = '0' or t.status is null) ";
		try {
			return CM.getDao().getPagerList("获取未处理告警列表", sql,
					new QuotaValueOnTimeRowWapper(), pager, condition,
					new Object[] {});
		} catch (DaoException e) {
			throw new DaoException(e);
		}
	}
	/**
	 * 获取未处理告警总数
	 * @return
	 * @throws DaoException
	 */
	public int getCountAlert(String ownId)throws DaoException {
		String sql = "select	count(*)  from 	 " + SI_TABLE("turbo_monitor_ontime")+" t   where t.needalert = '1' and (t.status = '0' or t.status is null)  and (? is null or t.owner_id=?)";
		try {
			return CM.getDao().queryForInt("获取未处理告警总数", sql,new Object[] {ownId,ownId});
		} catch (DaoException e) {
			throw new DaoException(e);
		}
	}
	/**
	 * 获取告警历史列表
	 * @param pager
	 * @param condition
	 * @return
	 * @throws DaoException
	 */
	public PagerData<QuotaValueHistory> historyAlertlist(Pager pager, WhereCondition condition)
			throws DaoException {
		String sql = "select id, quota_code, quota_name, alert_msg, mtime, alter_level,remark,has_alert_method,handler_time "
							 +" from (select t1.id, "
							 +"               t1.quota_code, "
							  +"              t2.name quota_name, "
							+"                t1.alert_msg, "
							+"                t1.mtime, "
							+"                t2.alter_level, "
							+"                t1.owner_id,t1.remark,t1.has_alert_method,t1.handler_time"
							+"           from  " + SI_TABLE("turbo_monitor_ontime")+"  t1 "
							+"           left join  " + SI_TABLE("turbo_monitor_quota")+"  t2 "
							+"             on t1.quota_code = t2.code "
							+"          where t1.needalert = '1' "
							 +"           and t1.status = '1' "
							+"         union "
							 +"        select t3.id, "
							  +"              t3.quota_code, "
							 +"      t4.name quota_name, "
							  +"              t3.alert_msg, "
							  +"              t3.mtime, "
							  +"              t4.ALTER_LEVEL, "
							  +"              t3.owner_id,t3.remark,t3.has_alert_method,t3.handler_time "
							  +"         from  " + SI_TABLE("turbo_monitor_history")+"  t3 "
							   +"        left join  " + SI_TABLE("turbo_monitor_quota")+"  t4 "
							 +"            on t3.quota_code = t4.code "
							   +"       where t3.needalert = '1') t where 1=1";
		try {
			return CM.getDao().getPagerList("获取告警历史列表", sql,
					new QuotaValueHistoryRowWapper(), pager, condition,
					new Object[] {});
		} catch (DaoException e) {
			throw new DaoException(e);
		}
	}
	/**
	 * 关闭告警
	 * @param id
	 * @return
	 * @throws DaoException
	 */
	public int closeAlert(String id) throws DaoException {
		int num = 0;
		try {
			String sql = "update  "+SI_TABLE("turbo_monitor_ontime")+" set  status='1',handler_time=sysdate,has_alert_method=? where id = ?";
			num = CM.getDao().update("关闭告警", sql,new Object[]{ALERT_PIPELINE.ADMIN_CLOSE.getCode(),id} );
		} catch (DaoException e) {
			throw new DaoException("关闭告警失败", e);
		}
		return num;
	}
	/**
	 * 批量关闭告警
	 * @param ids
	 * @return
	 * @throws DaoException
	 */
	public int batchCloseAlert(String[] ids) throws DaoException {
		int num = 0;
		try {
			Assert.noNullElements(ids);
			List<Object[]> params = new ArrayList<Object[]>();
			for(String id: ids){
				params.add(new Object[]{ALERT_PIPELINE.ADMIN_CLOSE.getCode(),id});
			}
			String sql = "update  "+SI_TABLE("turbo_monitor_ontime")+" set  status='1',handler_time=sysdate,mtime=sysdate, has_alert_method=? where id = ?";
			num = CM.getDao().batchUpdate("批量关闭告警", sql, params );
		} catch (DaoException e) {
			throw new DaoException("批量关闭告警失败", e);
		}
		return num;
	}
	/**
	 * 关闭告警
	 * @param ids
	 * @return
	 * @throws DaoException
	 */
	public int closeQuotaValueOnTime(QuotaValueOnTime quotaValueOnTime ) throws DaoException {
		int num = 0;
		try {
			quotaValueOnTime.setStatus(QuotaHadlerStatus.HAS_HANDLER.getCode());
			CM.getDao().updateModuleByIdExecuteNull("关闭已处理完成的告警", quotaValueOnTime);
		} catch (DaoException e) {
			throw new DaoException("关闭已处理完成的告警失败", e);
		}
		return num;
	}
	/**
	 * 定时删除已处理告警历史
	 * @param day
	 * @throws DaoException
	 */
	public void timingDelete(String day) throws DaoException {
		String msg = "";
		String sql = "delete  from " + SI_TABLE("turbo_monitor_history")
				+ " where (sysdate - mtime) >? ";
		try {
			CM.getDao().delete("定时删除已处理告警历史", sql, new Object[] {day});
		} catch (DaoException e) {
			msg = "定时删除已处理告警历史失败";
			logger.error(msg, e);
			throw new DaoException(msg, e);
		}
	}
	/**
	 * 管理节点交换监控 节点和通道状态
	 * @param codes　指标数据
	 * @param ownerId　对象id
	 * @return
	 * @throws DaoException
	 */
	public List<QuotaValueOnTime> getExchRelMonitorShow(String[] codes,String ownerId)throws DaoException {
		WhereCondition condition = new WhereCondition();
		condition.and().in("t1.quota_code", codes);
		condition.and().eq("t1.owner_id", ownerId);
		condition.and().eq("t1.needalert", "1");
		try {
			String sql = "select t1.quota_code,t2.name quota_name,t1.current_value1,t1.alert_msg from " + SI_TABLE("turbo_monitor_ontime")+" t1 " 
					+ " left join " + SI_TABLE("turbo_monitor_quota")+" t2  on t1.quota_code = t2.code"
					+ " where t1.mtime = (select max(mtime) from " + SI_TABLE("turbo_monitor_ontime")+" where quota_code = t1.quota_code and owner_id=t1.owner_id )" 
					+ " and (t1.status = '0' or t1.status is null) ";
			return CM.getDao().list("获取监控指标信息", sql,
					new QuotaValueOnTimeRowWapper(), condition, new Object[] {});
		} catch (DaoException e) {
			throw new DaoException("获取监控指标信息失败", e);
		}
	}
	/**
	 * 获取对象监控值
	 * @param quotaCode　指标编码
	 * @param ownerId　对象id
	 * @return
	 * @throws DaoException
	 */
	public QuotaValueOnTime getOnTime(String quotaCode,String ownerId)throws DaoException {
		try {
			String sql ="select distinct t2.name quota_name,t1.current_value1 from " + SI_TABLE("turbo_monitor_ontime")+" t1 " 
					+ " left join " + SI_TABLE("turbo_monitor_quota")+" t2  on t1.quota_code = t2.code where t1.quota_code=? and t1.owner_id=? " 
					+ " and t1.mtime = (select max(mtime) from " + SI_TABLE("turbo_monitor_ontime")+" where quota_code = t1.quota_code and owner_id=t1.owner_id)" 
					+ " and (t1.status = '0' or t1.status is null) ";
			return CM.getDao().get("获取监控指标信息", sql,
					new QuotaValueOnTimeRowWapper(), new Object[] {quotaCode,ownerId});
		} catch (DaoException e) {
			throw new DaoException("获取监控指标信息失败", e);
		}
		
	}
}
